package com.shaoyuwang;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.*;
import java.util.Scanner;

/**
 * 插入自增id
 */
public class LastInsertIdDemo {
    public static void main(String[] args) throws SQLException {
        MysqlDataSource db = new MysqlDataSource();
        db.setServerName("localhost");
        db.setPort(3306);
        db.setUser("root");
        db.setPassword("123456");
        db.setDatabaseName("lib_0403");
        db.setUseSSL(false);
        db.setCharacterEncoding("utf-8");
        db.setServerTimezone("Asia/Shanghai");

        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        try (Connection c = db.getConnection()) {

            String sql = "insert into readers (name) values (?)";

            // Statement.RETURN_GENERATED_KEYS 返回自增的键
            try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, name);

                ps.executeUpdate();

                try (ResultSet rs = ps.getGeneratedKeys()) {
                    if (rs.next()) {
                        int rid = rs.getInt(1);
                        System.out.println(rid + "|" + name);
                    }
                }
            }
        }
    }
}
